<?php

namespace App\Models;

use App\Traits\External;
use Carbon\Carbon;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use DateTimeInterface;

class Crm_Member extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory;
    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'crm_member';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    protected $fillable = [
        'agencyid','sn','username','gender','realname','mobile','weixin',
        'age','birthday','marry','education','height','weight','avatar',
        'school','job','salary','province','province_name','city','city_name',
        'area','area_name','reside_province','reside_province_name',
        'reside_city','reside_city_name','reside_area','reside_area_name',
        'house','car','blood','smoking','drinking','national','child','interest',
        'personality','zodiac','constellation','companytype','remark','ishidden',
        'status','checktimes','reason','makerid','tgid','belongid','serviceid','vipid','vipstart','vipend',
        'vvipid','vvipstart','vvipend','istop','source','type','loginnums','logintime',
        'allottime','followtime','isdrop','droptime','dropreason','dropremark','ispay','intro','evaluate','is_del'
    ];

    protected $appends = [
        'genderText','marryText','educationText','jobText','salaryText','houseText','carText',
        'typeText','intentionText','statusText','belongText','tgText','makerText','istopText','serviceText',
        'ishiddenText','ispayText','isfreezeText','sourceText','bloodText','companytypeText','drinkingText',
        'smokingText','zodiacText','constellationText','nationalText','childText','interestText',
        'personalityText'
    ];


    public function getGenderTextAttribute()
    {
        $genderArr = External::getParams('gender');
        return $genderArr[$this->gender];
    }

    public function getMarryTextAttribute()
    {

        if (!empty($this->marry)){
            $marryArr = External::getParams('marry');
            return $marryArr[$this->marry];
        }else{
            return '无';
        }

    }

    public function getEducationTextAttribute()
    {
        if (!empty($this->marry)){
            $educationArr = External::getParams('education');
            return $educationArr[$this->education];
        }else{
            return '无';
        }
    }

    public function getJobTextAttribute()
    {
        if (!empty($this->job)){
            $jobArr = External::getParams('job');
            return $jobArr[$this->job];
        }else{
            return '无';
        }
    }

    public function getSalaryTextAttribute()
    {
        if (!empty($this->salary)){
            $salaryArr = External::getParams('salary');
            return $salaryArr[$this->salary];
        }else{
            return '无';
        }
    }

    public function getHouseTextAttribute()
    {
        if (!empty($this->house)){
            $houseArr = External::getParams('house');
            return $houseArr[$this->house];
        }else{
            return '无';
        }
    }

    public function getCarTextAttribute()
    {
        if (!empty($this->car)){
            $carArr = External::getParams('car');
            return $carArr[$this->car];
        }else{
            return '无';
        }
    }

    public function getTypeTextAttribute()
    {
        return $this->type == 0 ? '线下用户' : '线上用户';
    }

    public function getIntentionTextAttribute()
    {
        if (!empty($this->intention)){
            $intentionArr = External::getParams('intention');
            return $intentionArr[$this->intention];
        }else{
            return '无';
        }
    }

    public function getStatusTextAttribute()
    {
        if($this->status == 'wait'){
            return '待审核';
        }elseif($this->status == 'pass'){
            return '通过';
        }else{
            return '未通过';
        }
    }

    public function getBelongTextAttribute()
    {
        if ($this->belongid){
            $user = Crm_User::find($this->belongid);
            return $user->username;
        }else{
            return '无';
        }
    }

    public function getTgTextAttribute()
    {
        if ($this->tgid){
            $user = Crm_User::find($this->tgid);
            return $user->username;
        }else{
            return '无';
        }
    }

    public function getMakerTextAttribute()
    {
        if ($this->makerid){
            $user = Crm_User::find($this->makerid);
            return $user->username;
        }else{
            return '无';
        }
    }

    public function getServiceTextAttribute()
    {
        if ($this->serviceid){
            $user = Crm_User::find($this->serviceid);
            return $user->username;
        }else{
            return '无';
        }
    }

    public function getIstopTextAttribute()
    {
        if($this->istop == 0){
            return '未置顶';
        }elseif($this->istop == 1){
            return '已置顶';
        }else{
            return '已过期';
        }
    }

    public function getIshiddenTextAttribute()
    {
        if($this->ishidden == 1){
            return '公开相亲';
        }elseif($this->ishidden == 2){
            return '私密相亲';
        }else{
            return '已脱单';
        }
    }

    public function getIspayTextAttribute()
    {
        return $this->ispay == 'Y' ? '付费' : '免费';
    }

    public function getIsfreezeTextAttribute()
    {
        return $this->isfreeze == 'Y' ? '已冻结' : '未冻结';
    }

    public function getSourceTextAttribute()
    {
        if (!empty($this->source)){
            $sourceArr = External::getParams('source');
            return $sourceArr[$this->source];
        }else{
            return '无';
        }
    }

    public function getBloodTextAttribute()
    {
        if (!empty($this->blood)){
            $bloodArr = External::getParams('blood');
            return $bloodArr[$this->blood];
        }else{
            return '无';
        }
    }

    public function getCompanytypeTextAttribute()
    {
        if (!empty($this->companytype)){
            $companytypeArr = External::getParams('companytype');
            return $companytypeArr[$this->blood];
        }else{
            return '无';
        }
    }

    public function getDrinkingTextAttribute()
    {
        if (!empty($this->drinking)){
            $drinkingArr = External::getParams('drinking');
            return $drinkingArr[$this->drinking];
        }else{
            return '无';
        }
    }

    public function getSmokingTextAttribute()
    {
        if (!empty($this->smoking)){
            $smokingArr = External::getParams('smoking');
            return $smokingArr[$this->smoking];
        }else{
            return '无';
        }
    }

    public function getZodiacTextAttribute()
    {
        if (!empty($this->zodiac)){
            $zodiacArr = External::getParams('zodiac');
            return $zodiacArr[$this->zodiac];
        }else{
            return '无';
        }
    }

    public function getConstellationTextAttribute()
    {
        if (!empty($this->constellation)){
            $constellationArr = External::getParams('constellation');
            return $constellationArr[$this->constellation];
        }else{
            return '无';
        }
    }

    public function getNationalTextAttribute()
    {
        if (!empty($this->national)){
            $nationalArr = External::getParams('national');
            return $nationalArr[$this->national];
        }else{
            return '无';
        }
    }

    public function getChildTextAttribute()
    {
        if (!empty($this->child)){
            $childArr = External::getParams('child');
            return $childArr[$this->child];
        }else{
            return '无';
        }
    }

    public function getInterestTextAttribute()
    {
        if (!empty($this->interest)){
            $interestTextArr = [];
            $interestArr = External::getParams('interest');
            $i = explode(',',$this->interest);
            foreach ($i as $v)
            {
                array_push($interestTextArr,$interestArr[$v]);
            }
            return $interestTextArr;
        }else{
            return [];
        }
    }

    public function getPersonalityTextAttribute()
    {
        if (!empty($this->personality)){
            $personalityTextArr = [];
            $personalityArr = External::getParams('personality');
            $p = explode(',',$this->personality);
            foreach ($p as $v)
            {
                array_push($personalityTextArr,$personalityArr[$v]);
            }
            return $personalityTextArr;
        }else{
            return [];
        }
    }

    public function scopeNodel($query)
    {
        return $query->where('is_del', 'N');
    }

    public function scopeNodrop($query)
    {
        return $query->where('isdrop', 'N');
    }

    public function scopeYesdrop($query)
    {
        return $query->where('isdrop', 'Y');
    }

    protected $hidden = [
        'is_del',
    ];

    public static function _generateSn($prefix = '',$length)
    {
        list($usec, $sec) = explode(' ', microtime());
        return $prefix . substr($usec, 3, $length);
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function hasOneMemberAuth()
    {
        return $this->hasOne('App\Models\Crm_Member_Auth', 'mid', 'id');
    }

    public function hasOneMemberFollow()
    {
        return $this->hasOne('App\Models\Crm_Member_Follow', 'mid', 'id');
    }

    public function hasOneMemberRotate()
    {
        return $this->hasOne('App\Models\Crm_Member_Rotate', 'mid', 'id');
    }

    public function hasOneMemberAnnex()
    {
        return $this->hasOne('App\Models\Crm_Member_Annex', 'mid', 'id');
    }

    public static function getFilter($filter)
    {
        $model = self::query();
        //判断查询条件是否有下次跟进时间，若有则关联跟进表
        if(isset($filter['nextStartTime']) && !empty($filter['nextStartTime']) && isset($filter['nextEndTime']) && !empty($filter['nextEndTime'])) {
            $model->whereHas('hasOneMemberFollow',function ($query) use ($filter){
                $query->where('nexttime','>=',$filter['nextStartTime'])
                    ->where('nexttime','<=',$filter['nextEndTime'])
                    ->where('is_del','N');
            });
        }

        //判断查询条件是否有mode,并且是否为2
        if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 2){
            //今日需跟进
            $model->whereHas('hasOneMemberFollow',function ($query) use ($filter){
                $query->where('nexttime','>=',Carbon::now()->toDay()->toDateTimeString())
                    ->where('nexttime','<=',Carbon::now()->endOfDay()->toDateTimeString())
                    ->where('is_del','N');
            });
        }

        //判断查询条件是否有mode,并且是否为6
        if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 6){
            //有预约跟进
            $model->whereHas('hasOneMemberFollow',function ($query) use ($filter){
                $query->whereNotNull('nexttime')
                    ->where('is_del','N');
            });
        }

        //判断查询条件是否有认证项，若有则关联认证表
        if(isset($filter['auth']) && !empty($filter['auth'])){
            $auth = explode(',',$filter['auth']);

            $model->whereHas('hasOneMemberAuth',function ($query) use ($auth){
                if(in_array(1,$auth))
                    $query->where('flag','pass');
                if(in_array(2,$auth))
                    $query->where('eflag','pass');
                if(in_array(3,$auth))
                    $query->where('hflag','pass');
                if(in_array(4,$auth))
                    $query->where('cflag','pass');
                if(in_array(5,$auth))
                    $query->where('sflag','pass');
            });
        }
        //判断查询条件是否有原归属人，若有则关联流转表，一对一关联最新一条数据
        if(isset($filter['oldbelongid']) && !empty($filter['oldbelongid'])){
            $model->whereHas('hasOneMemberRotate',function ($query) use ($filter){
                $query->where('olduserid',$filter['oldbelongid']);
                $query->where('islast','Y');
            });
        }

        $model->where(function ($query) use ($filter){

            if (isset($filter['id']) && !empty($filter['id'])) {
                $query->where('id', $filter['id']);
            }

            if (isset($filter['username']) && !empty($filter['username'])) {
                $query->where('username', 'LIKE', '%' . $filter['username'] . '%');
            }

            if (isset($filter['realname']) && !empty($filter['realname'])) {
                $query->where('realname', 'LIKE', '%' . $filter['realname'] . '%');
            }

            if (isset($filter['mobile']) && !empty($filter['mobile'])) {
                $query->where('mobile', 'LIKE', '%' . $filter['mobile'] . '%');
            }

            if (isset($filter['gender']) && !empty($filter['gender'])) {
                $query->where('gender', $filter['gender']);
            }

            if (isset($filter['maxAge']) && !empty($filter['maxAge'])) {
                $query->where('age', '<=', $filter['maxAge']);
            }

            if (isset($filter['minAge']) && !empty($filter['minAge'])) {
                $query->where('age', '>=',$filter['minAge']);
            }

            if (isset($filter['maxHeight']) && !empty($filter['maxHeight'])) {
                $query->where('height', '<=', $filter['maxHeight']);
            }

            if (isset($filter['minHeight']) && !empty($filter['minHeight'])) {
                $query->where('height', '>=',$filter['minHeight']);
            }

            if (isset($filter['maxWeight']) && !empty($filter['maxWeight'])) {
                $query->where('weight', '<=', $filter['maxWeight']);
            }

            if (isset($filter['minWeight']) && !empty($filter['minWeight'])) {
                $query->where('weight', '>=',$filter['minWeight']);
            }

            if (isset($filter['status']) && !empty($filter['status'])) {
                $query->where('status', $filter['status']);
            }

            if (isset($filter['marry']) && !empty($filter['marry'])) {
                $query->where('marry', $filter['marry'] );
            }

            if (isset($filter['education']) && !empty($filter['education'])) {
                $query->where('education',  $filter['mobile'] );
            }

            if (isset($filter['house']) && !empty($filter['house'])) {
                $query->where('house', $filter['house'] );
            }

            if (isset($filter['car']) && !empty($filter['car'])) {
                $query->where('car',  $filter['car'] );
            }

            if (isset($filter['salary']) && !empty($filter['salary'])) {
                $query->where('salary',  $filter['salary'] );
            }

            if (isset($filter['vvipid']) && !empty($filter['vvipid'])) {
                $query->where('vvipid',  $filter['vvipid'] );
            }

            if (isset($filter['province']) && !empty($filter['province'])) {
                $query->where('province',  $filter['province'] );
            }
            if (isset($filter['city']) && !empty($filter['city'])) {
                $query->where('city',  $filter['city'] );
            }
            if (isset($filter['area']) && !empty($filter['area'])) {
                $query->where('area',  $filter['area'] );
            }

            if (isset($filter['reside_province']) && !empty($filter['reside_province'])) {
                $query->where('reside_province',  $filter['reside_province'] );
            }
            if (isset($filter['reside_city']) && !empty($filter['reside_city'])) {
                $query->where('reside_city',  $filter['reside_city'] );
            }
            if (isset($filter['reside_area']) && !empty($filter['reside_area'])) {
                $query->where('reside_area',  $filter['reside_area'] );
            }

            if (isset($filter['istop']) && !empty($filter['istop'])) {
                $query->where('istop', $filter['istop']);
            }

            if (isset($filter['job']) && !empty($filter['job'])) {
                $query->where('job', $filter['job']);
            }

            if (isset($filter['ishidden']) && !empty($filter['ishidden'])) {
                $query->where('ishidden', $filter['ishidden']);
            }

            if (isset($filter['isfreeze']) && !empty($filter['isfreeze'])) {
                $query->where('isfreeze', $filter['isfreeze']);
            }

            if (isset($filter['belongid']) && !empty($filter['belongid'])) {
                $query->where('belongid', $filter['belongid']);
            }

            if (isset($filter['tgid']) && !empty($filter['tgid'])) {
                $query->where('tgid', $filter['tgid']);
            }

            if (isset($filter['source']) && !empty($filter['source'])) {
                $query->where('source', $filter['source']);
            }

            if (isset($filter['followStartTime']) && !empty($filter['followStartTime'])) {
                $query->where('followtime', '<=', $filter['followStartTime']);
            }

            if (isset($filter['followEndTime']) && !empty($filter['followEndTime'])) {
                $query->where('followtime', '>=',$filter['followEndTime']);
            }

            if (isset($filter['startTime']) && !empty($filter['startTime'])) {
                $query->where('created_at', '<=', $filter['startTime']);
            }

            if (isset($filter['endTime']) && !empty($filter['endTime'])) {
                $query->where('created_at', '>=',$filter['endTime']);
            }

            if (isset($filter['loginStartTime']) && !empty($filter['loginStartTime'])) {
                $query->where('logintime', '<=', $filter['loginStartTime']);
            }

            if (isset($filter['loginEndTime']) && !empty($filter['loginEndTime'])) {
                $query->where('logintime', '>=',$filter['loginEndTime']);
            }

            if (isset($filter['allotStartTime']) && !empty($filter['allotStartTime'])) {
                $query->where('allottime', '<=', $filter['allotStartTime']);
            }

            if (isset($filter['allotEndTime']) && !empty($filter['allotEndTime'])) {
                $query->where('allottime', '>=',$filter['allotEndTime']);
            }

            if (isset($filter['type']) && !empty($filter['type'])) {
                $query->where('type', $filter['type']);
            }

            //今日已跟进
            if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 1){
                $query->where('followtime','>=',Carbon::now()->toDay()->toDateTimeString())
                    ->where('followtime','<=',Carbon::now()->endOfDay()->toDateTimeString());
            }

            //今日新分配
            if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 3){
                $query->where('allottime','>=',Carbon::now()->toDay()->toDateTimeString())
                    ->where('allottime','<=',Carbon::now()->endOfDay()->toDateTimeString());
            }

            //从未跟进
            if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 4){
                $query->whereNull('followtime');
            }

            //近3日未跟进
            if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 5){
                $query->where('followtime','>=',Carbon::now()->toDay()->subDay(3)->toDateTimeString())
                    ->where('followtime','<=',Carbon::now()->toDay()->toDateTimeString());
            }

            //3日后将坠海
            if(isset($filter['mode']) && !empty($filter['mode']) && $filter['mode'] == 7){
                $query->whereDate('droptime',Carbon::now()->addDay(3)->toDateString());
            }
            $query->where('agencyid', $filter['aid']);

        });

        return $model;
    }

    public static function getSearch($filter)
    {
        return self::where(function ($query) use ($filter){
            $query->where('id',$filter['keyword'])
                ->orWhere('mobile','LIKE','%'.$filter['keyword'].'%');

        })->where('agencyid',$filter['aid'])->where('ishidden','!=' ,3);
    }
}
